package com.wy0924.serlet;

import com.wy0924.bean.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@WebServlet("/login.do")
public class LoginServlet extends BaseServlet {

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String regex = "^\\w{2,14}$";
        if (!username.matches(regex)){
            resp.sendRedirect("./login.jsp");
            resp.getWriter().write("登陆失败");
            return;
        }
        User user = new User(username, req.getRemoteHost(), new SimpleDateFormat("yyyy-MM-dd HH:sss:SSS").format(new Date()));
        req.getSession().setAttribute("user",user);
        resp.getWriter().write("0");

    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("user");
        resp.getWriter().write("0");



    }

    protected void remove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        if (!"192.168.4.8".trim().equals(req.getRemoteHost())){
            resp.getWriter().write("-1");
        }else {
            ServletContext servletContext = req.getServletContext();
            ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList");
            if (userList == null) {
                resp.getWriter().write("1");
                return;
            }
            String ip = req.getParameter("IP");
            userList.remove(new User(null, ip,null));
            resp.getWriter().write("0");
        }



    }
}
